import Taro, { Component, useState, useEffect, useRouter } from '@tarojs/taro';
import './index.scss';
import { View, Input, Image } from '@tarojs/components';
import Bg from './img/bg1.png';
import Title from './img/title.png';
import Success from './img/success.png';
import close1 from './img/close.png';
import xinfeng from './img/xinfeng.png';
import ordinary1 from './img/ordinary1.png';
import ordinary2 from './img/ordinary2.png';
import ordinary3 from './img/ordinary3.png';
import righticon from './img/righticon.png';
import lefticon from './img/lefticon.png';

import { getUserInfo } from '../../../services/user';
import { fullImgUrl, timeFormat, getQueryString } from '../../../utils/utils';

import CouponTitle from '../../../static/public/success.png';
import classnames from 'classnames';
import Tips from '../../../components/tips-modal';
import NavigationBar from '../../../components/navigationBar/index';
import { cardMember, cardConvert, couponConvert } from '../../../services/card';

function Bangdingcard(props) {
  const navigationBarHeight = Taro.getStorageSync('navigationBarHeight');
  const [password, setPassword] = useState('');
  const [cardno, setCardno] = useState('');
  const [isAgreement, setIsAgreement] = useState('');
  const [iscode, setIscode] = useState('');
  const [animationData, setAnimationData] = useState('');
  const [isSuccess, setIsSuccess] = useState('');
  const [toSuccess, setToSuccess] = useState('');

  const [isTip, setIstip] = useState(Taro.getStorageSync('setting').is_tip);
  const [type, setType] = useState(''); // 判断兑换类型
  const [bpic, setBpic] = useState(''); // 判断兑换类型
  const [title1, setTitle1] = useState(''); // 判断兑换类型
  const [word, setWord] = useState(''); // 判断兑换类型
  const [word1, setWord1] = useState('');
  const [word2, setWord2] = useState('');

  const [checked, setChecked] = useState(false); // 判断兑换类型

  const [viptitle, setViptitle] = useState(''); // 判断兑换类型
  const uerInfo = Taro.getStorageSync('userInfo');

  const router = useRouter();



  useEffect(() => {
    console.log(uerInfo, word2)

    Taro.showToast({
      title: uerInfo,
      icon: 'none',
    });
    setType(router.params.type);
    const pic = Taro.getStorageSync('MemberPic');
    var card_no = Taro.getStorageSync('card_no_home');

    setCardno(card_no)
    if (uerInfo.member_level == 2) {
      setWord1('您已是红宝石会员')
      setWord2('无需再次绑定会员卡')
      setToSuccess(true)
    }
    pic.list.forEach(ele => {
      if (uerInfo.member_level == 0 && ele.key == "member_zero_binding_pic") {
        setBpic(ele.path)
      } else if (uerInfo.member_level == 1 && ele.key == "member_one_binding_pic") {
        setBpic(ele.path)
        setViptitle('VIP贵宾会员')
      } else if (uerInfo.member_level == 2 && ele.key == "member_two_binding_pic") {

        setBpic(ele.path)
        setViptitle('红宝石会员')

      }
      if (ele.key == 'member_code_window') {
        setTitle1(ele.path)
      }
    });
    const word = Taro.getStorageSync('Memberword');
    word.list.forEach(ele => {
      if (ele.key == 'member_rule') {
        setWord(ele.data)
      }
    });
  }, []);
  function getimage() {

  }
  function handleText(e) {
    setPassword(e.target.value.trim());
  }
  function handleText1(e) {
    setCardno(e.target.value.trim());
  }
  function convert() {
    console.log(checked)
    if (!password) {
      Taro.showToast({
        title: '请输入兑换码',
        icon: 'none',
      });
    } else {
      if (checked == false) {
        cardMember({
          exchange_no: password,
          card_no: cardno
        }).then(res => {
          if (res == "ok") {
            getUserInfo({
              id: Taro.getStorageSync('userInfo').id + '',
            }).then(res => {
              Taro.setStorageSync('userInfo', res);
              const pic = Taro.getStorageSync('MemberPic');

              pic.list.forEach(ele => {
                if (res.member_level == 0 && ele.key == "member_zero_binding_pic") {
                  setBpic(ele.path)
                } else if (res.member_level == 1 && ele.key == "member_one_binding_pic") {
                  setBpic(ele.path)
                  setViptitle('VIP贵宾会员')
                } else if (res.member_level == 2 && ele.key == "member_two_binding_pic") {

                  setBpic(ele.path)
                  setViptitle('红宝石会员')

                }
              });
              setIsSuccess(true)

            })
          } else {
            console.log(res)
            setWord1(res.msg_one)
            setWord2(res.msg_two)

            setToSuccess(true)
          }
          // Taro.navigateTo({
          //   url: `/pages/goods-detail/index?code=${password}`,
          // });
        });
        // } else {
        //   couponConvert({
        //     exchange_no: password,
        //     coupon_no: Taro.getStorageSync('card_no'),
        //   }).then(res => {
        //     Taro.navigateTo({
        //       url: `/subPackageWork/pages/roll-shop-list/index?code=${password}`,
        //     });
        //   });
        //   // Taro.navigateTo({
        //   //   url: `/subPackageWork/pages/roll-shop-list/index?code=${password}`,
        //   // });
      } else {
        Taro.showToast({
          title: '请同意规则',
          icon: 'none',
        });
      }
    }
  }
  function agreeMent() {
    setIsAgreement(true)
  }
  function close() {
    setIsAgreement(false)

  }
  function knowclose() {
    setIscode(false)
  }
  function toshop() {
    Taro.navigateTo({
      url: "/subPacKagebWork/pages/vip-goods-list/index?goods_id=7"
    })
  }
  function boxchange() {
    if (checked === true) {
      setChecked(false)

    } else {
      setChecked(true)
    }

  }
  function inputTap() {
    setIscode(true)
    const animation = Taro.createAnimation({
      duration: 300,
      timingFunction: 'ease',
      delay: 0
    });
    animation.bottom(300).step()
    setAnimationData(animation.export())
  }
  function backpage() {
    Taro.reLaunch({ url: '/pages/home/index' });
  }
  return (
    <View className='exchange' style={`margin-top: ${navigationBarHeight}`}>
      <NavigationBar text='绑定会员卡' type="bindcard" />

      {/* <Image className='bg' src={Bg} /> */}
      <View className='content'>
        {uerInfo.member_level != 0 ? (
          <View className="imageDad">
            <View className="imageDiv">
              <Image className='widthFix' src={xinfeng} />
              <View className='image-title' >您已是{viptitle}</View>
              <View className='image-vip' style={`background-image: url(${fullImgUrl(bpic)})`}>
                {uerInfo.member_level == 1 ? (
                  <View className='image-title2' >可升级至红宝石会员，并继承抵扣额度</View>

                ) : (
                    <View className='image-title2' >绑定此卡将继承卡内的抵扣额度</View>

                  )}
                <View className='image-title3' >{viptitle}</View>
                <View className='image-title4' >NO.{uerInfo.card_no}</View>
                <View className='image-title5' >
                  ￥
                <View className='image-title-child' >
                    {uerInfo.balance}

                  </View>
                  <View className='image-title-child1' >
                    抵扣余额
</View>
                </View>

              </View>

            </View>
          </View>
        ) : (
            <View className="ordinaryDiv">
              <Image className='widthFix' src={xinfeng} />
              <Text className='ordinary-title' >感谢您</Text>
              <Text className='ordinary-title1' >成为中鹿岛会员</Text>
              <Text className='ordinary-title2' >您将享受如下特权</Text>
              <View className='ordinary-vip'>
                <Image className='ordinary-img1' src={ordinary1} />
                <Image className='ordinary-img1' src={ordinary2} />
                <Image className='ordinary-img1' src={ordinary3} />
              </View>
              <View className='ordinary-vip1'>
                <Text className='ordinary-title3' >抵扣额度</Text>
                <Text className='ordinary-title4' >会员优选</Text>
                <Text className='ordinary-title5' >优先发货</Text>
              </View>
            </View>
          )}
        <View className='code-box1' >
          <View onClick={inputTap} className="vip-code">会员卡号</View>
          <Input placeholder-class="placehold" value={cardno} placeholder='请输入会员卡号' className='code' onInput={handleText1} />
        </View>
        <View className='code-box' >
          <View onClick={inputTap} className="vip-code">会 员 码</View>
          <Input placeholder-class="placehold" placeholder='刮开卡背涂层，输入会员码' className='code' onInput={handleText} />
        </View>
        <CheckboxGroup class="info" onChange={boxchange}>
          <View className="code-boxs" >
            <Checkbox class="check-box" value={checked} checked='false' onChange={boxchange} /><text class="user-agrees"> 我同意</text><View class="user-agree"
              onClick={agreeMent}> 《中鹿岛会员兑换规则》</View>。
          </View>
        </CheckboxGroup>
        {isAgreement == true && (
          <view class="agreement-text">
            <span style="line-height:100rpx;text-align:center;border-bottom:1rpx solid #fff;display:block;margin:0 auto;font-size:40rpx">兑换规则</span>
            <Text className="rich-text" decode="true">{word}</Text>
            {/* <span style="width:648rpx;margin: 0 auto;margin-top:20rpx">2.成为会员后，您将获得专属商城，并享受会员折扣；</span>
            <span style="width:648rpx;margin: 0 auto;margin-top:20rpx">3.卡内含抵扣额度，用于购买中鹿岛指定产品，不可折现；</span>
            <span style="width:648rpx;margin: 0 auto;margin-top:20rpx">4.若您已是会员，再次绑定将仅继承卡内的抵扣额度；</span>
            <span style="width:648rpx;margin: 0 auto;margin-top:20rpx">5.会员折扣和抵扣额度可同时使用；</span>
            <span style="width:648rpx;margin: 0 auto;margin-top:20rpx">6.本公司拥有最终解释权；</span> */}
            <Image class="btn-box" onClick={close} src={close1} />
          </view>
        )}
        {iscode == true && (
          <View class="topcode" animation={animationData}>
            <Image onClick={knowclose} className='topcode-img' src={fullImgUrl(title1)} />
            {/* 
            <View className="know-dad">
              <Image className='title1' src={} />
              <View class="know-box" >我知道了</View>
            </View> */}
          </View>
        )}
        {toSuccess == true && (
          <View class="topsuccess" animation={animationData}>
            <View className="imageDiv">
              <Image className='widthFix' src={xinfeng} />
              <Image className='righticon' src={righticon} />
              <Image className='lefticon' src={lefticon} />
              <View class="successtexts">温馨提示</View>
              <View className="rich-texts">{word1}</View>
              <View className="rich-texts">{word2}</View>
            </View>
            <View
              className="submit-btn"
              onClick={
                toshop
              }>
              前 往 会 员 活 动 专 区
      </View>
          </View>
        )}
        {isSuccess == true && (
          <View class="topsuccess" animation={animationData}>
            <Image className="topimage-success" src={Success} />
            <View class="successtext">绑定成功</View>
            <View class="body-text-success">
              <View class="successtext1">您已成功绑定</View>

              {/* {uerInfo.member_level != 0 ? ( */}
              <View className='success-images' style={`background-image: url(${fullImgUrl(bpic)})`}>
                <View className='success-title3' >{viptitle}</View>
                <View className='success-title4' >NO.{uerInfo.card_no}</View>
                <View className='success-title5' >
                  ￥
                <View className='success-title-child' >
                    {uerInfo.balance}

                  </View>
                  <View className='success-title-child1' >
                    抵扣余额
</View>


                </View>
              </View>
              {/* // ) : (<View className="imageDad" >
              //   <Image className='widthFix' src={fullImgUrl(bpic)} />

              // </View>
              //   )} */}
              <View class="successtext2">您可进入"我的"查看会员信息</View>
              <View class="successtext3">也可进入专属会员商城购买</View>

            </View>
            <View
              className="submit-btn"
              onClick={
                backpage
              }>
              确 认
      </View>
          </View>
        )}
        <View
          className={classnames({
            'submit-btn': true,
            'active-btn': password,
          })}
          onClick={
            convert
          }>
          立 即 绑 定
      </View>
        <View
          className="close-btn"
          onClick={
            backpage
          }>
          取 消
      </View>
      </View>
      {/* {isTip ? <Tips onClose={() => setIstip(false)} /> : null} */}
    </View>
  );
}


Bangdingcard.config = {
  navigationBarTitleText: '兑换',
};

export default Bangdingcard;